<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItems" v-permission="'material.add'">任务创建
    </el-button>
    <div class="filter-container">
      <el-input style="width: 260px;" placeholder="输入名称/编码按回车" clearable class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.queryString">
      </el-input>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出 </el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns">
      <template v-slot:content="v">
        <span v-if="v.key == 'task_status'" class="text-label" :style="{background:taskStatusColor[v.row[v.key]]}">
          {{taskStatus[v.row[v.key]] ? taskStatus[v.row[v.key]].label : ''}}
        </span>
        <span v-else-if="v.key=='audit_result'">
          {{v.row[v.key]== 'Y'?'通过':v.row[v.key]== 'N'?'不通过':''}}

        </span>

        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation='v'>
        <a href="javascript:;" class="text-yellow" @click.stop="taskClaim(v.row)">任务认领</a>
        <a href="javascript:;" class="text-yellow" @click.stop="addUserClick(v.row,1)">指派</a>
        <a href="javascript:;" class="text-yellow" @click.stop="addUserClick(v.row,0)">转派</a>
        <a href="javascript:;" class="text-green" @click.stop="taskMaintain(v.row)">保养维护</a>
        <a href="javascript:;" class="text-green" @click.stop="toAudit(v.row)">审核</a>
        <a href="javascript:;" class="text-blue" @click.stop="editItemTask(v.row)">编辑</a>
        <a style="margin-left:5px;" href="javascript:;" class="text-red" @click.stop="deleteItem(v.row)">删除</a>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>

    <el-dialog :title="data.id ? '编辑' : '创建'" :width="formProps.dialogWidth" :close-on-click-modal="false"
      :visible.sync="editFormVisible" :before-close="beforClose">
      <div style="padding-right: 100px">
        <el-form :model="data" v-bind="formProps">
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备编号">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>设备编号</span>
                </span>
                <el-select v-model="data.machine_id" clearable filterable style="width: 100%">
                  <el-option v-for="o in machineList" :key="o.value" :label="o.label" :value="o.value" multiple
                    filterable remote reserve-keyword :remote-method="getMachinelist"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="保养岗位">

                <el-cascader style="width: 100%" v-model="data.handler_post_id" :options="userData" :props="userProps"
                  clearable>
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保养审核岗位">
                <el-cascader style="width: 100%" v-model="data.audit_post_id" :options="userData" :props="userProps"
                  clearable>
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="点检项">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>点检项</span>
                </span>
                <el-button type="primary" class="mb-5" @click="addspotCheck">添加</el-button>
                <el-button type="danger" class="mb-5" @click="delectspotCheck">删除</el-button>
                <br>
                <span>
                  可以多选删除
                </span>
                <z-table :list="spotCheckList" :tableProps="dianjiantableProps" :columns="dianjiancolumns"
                  @selection-change='selectionChange'>
                  <template v-slot:content="v">
                    <span v-if="v.key == 'method'">
                      {{getMatchingData(v.row[v.key],'method')}}
                    </span>
                    <span v-else-if="v.key=='pattern'">
                      {{v.row[v.key]== 0 ? '勾选' :'填值'}}
                    </span>
                    <span v-else>{{ v.row[v.key] }}</span>
                  </template>
                </z-table>
              </el-form-item>

            </el-col>
          </el-row>
        </el-form>

        <div class="text-right">
          <el-button @click="beforClose">取消</el-button>
          <el-button type="primary" @click="submits">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 保养项 -->
    <add-spot-check :maintainShow='maintainShows' :addspotCheckShow="addspotCheckShow" :spotCheckIds='spotCheckIds'
      @addItem="addMaintainItem" />
    <!-- 保养维护 -->
    <task-maintenance :maintainShow="maintainShow" :taskrowStatas='taskrowStatas' :taskList="taskList"
      :replaceList="replaceList" :replaceData="replaceData" @saveTask="saveTask" @taskAuditComfirm='taskAuditComfirm' />
    <!-- 指派/转派 -->
    <use-select v-if="selectVisible" ref="useselect" @closed="useSelectClose" @change="useSelectChange">
    </use-select>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import AddSpotCheck from '@/views/tpm/components/addSpotCheck'
import TaskMaintenance from '@/views/tpm/components/taskMaintenance.vue'
import useSelect from '@/components/Select'
export default {
  name: 'maintenanceTasks',
  mixins: [commonMixin],
  components: { AddSpotCheck, TaskMaintenance, useSelect },
  props: {},
  data() {
    return {
      query: {
        type_id: '',
        page: 1,
        size: 10,
      },
      api: this.$api.TpmMaintenanceTask,
      baseUrl: this.$api.baseUrl,
      postForList: true,
      name: '保养任务',
      tableProps: {
        border: true,
        opsColWith: 340,
        fixed: false,
        hideOperations: false,
      },
      spotCheckIds: [],
      spotCheckList: [],
      methodOptions: [],
      columns: [
        { title: '设备编号', key: 'machine_type_name', width: 100, fixed: 'left' },
        { title: '任务编号', key: 'task_code', width: 100, fixed: 'left' },
        { title: '保养时间', key: 'plan_time', width: 100 },
        { title: '任务类型', key: 'task_type', width: 100 },
        { title: '保养开始时间', key: 'start_time', width: 140 },
        { title: '保养结束时间', key: 'end_time', width: 140 },
        { title: '保养岗位', key: 'handler_post_name', width: 100 },
        { title: '状态', key: 'task_status', width: 100 },
        { title: '保养人', key: 'owner', width: 100 },
        { title: '保养审核岗位', key: 'audit_post_name', minWidth: 100 },
        { title: '审核人', key: 'audit' },
        { title: '审核结果', key: 'audit_result' },
        { title: '结果说明', key: 'audit_note' },
        { title: '审核时间', key: 'audit_time' },
        { title: '指派/转派人', key: 'assigned', width: 100 },
        { title: '指派时间', key: 'assigned_time' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],
      initData: {},
      // 上传数据
      formData: new FormData(),
      removeFiles: [], // 要被删除的附件id
      // 指派/转派
      selectVisible: false,
      userId: '',
      // 人员的选择
      userProps: {
        emitPath: false,
      },
      userData: [],
      delitems: [],
      machineList: [],
      addUserType: null,
      // 有点检项后点检项table
      addspotCheckShow: false,
      dianjiantableProps: {
        border: true,
        opsColWith: 80,
        fixed: false,
        hideOperations: true,
        selection: {
          showSelection: true,
        },
      },
      dianjiancolumns: [
        { title: '设备类型', key: 'machine_type_name' },
        { title: '保养内容', key: 'content' },
        { title: '保养标准', key: 'standard' },
        { title: '保养方法', key: 'method' },
        { title: '保养形式', key: 'pattern' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],
      taskStatus: [
        { label: '待认领', value: 0 },
        { label: '待保养', value: 1 },
        { label: '保养中', value: 2 },
        { label: '待审核', value: 3 },
        { label: '已完成', value: 4 },
      ],
      taskStatusColor: ['#e6a23c', '#e6a23c', '#409eff', '#e6a23c', '#67c23a'],
      // 维护
      maintainShow: false,
      taskList: [],
      taskId: '',
      taskrowStatas: 0,
      // 添加保养项
      maintainShows: false,
      replaceData: {},
      replaceList: [],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.research()
    this.getpositions()
    this.post()
    this.getMachinelist()
  },
  mounted() {},
  methods: {
    // 删除点检任务
    delectspotCheck() {
      // 从数组arr中删除数组to_remove中存在的元素
      let newArr = this.spotCheckList.filter((x) => !this.deleteSpotList.some((item) => x.id === item.id))
      let delArr = this.spotCheckList.filter((x) => this.deleteSpotList.some((item) => x.id === item.id))
      this.delitems = delArr
      this.spotCheckList = newArr
      this.deleteSpotList = []
    },
    beforClose() {
      this.spotCheckList = []
      this.editFormVisible = false
    },
    // 任务认领
    taskClaim(v) {
      this.$confirm('是否确定认领此任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$request(this.api + 'TaskClaim/' + v.id, {}, 'post').then((r) => {
            this.$message.success('认领成功!')
            this.research()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消认领',
          })
        })
    },
    // 获取设备
    getMachinelist(val) {
      let Data = {
        page: 1,
        size: 100,
        machine_code: val ? val : '',
      }
      this.$request(this.baseUrl + 'Tpm/Machine/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.machineList = list.map((i) => ({
          label: `${i.machine_code} ${i.machine_name}`,
          value: i.id,
        }))
      })
    },
    // 添加点检项
    addspotCheck() {
      this.addspotCheckShow = true
      this.maintainShows = true
      this.spotCheckIds = []
      this.spotCheckList.forEach((i) => {
        this.spotCheckIds.push(i.item_id)
      })
    },
    // 确定添加点检项
    addMaintainItem(val) {
      let tmp = val.map((i) => ({
        item_id: i.id,
        content: i.content,
        create_time: i.create_time,
        create_user: i.create_user,
        id: i.id,
        is_valid: i.is_valid,
        machine_type_code: i.machine_type_code,
        machine_type_name: i.machine_type_name,
        method: i.method,
        modify_time: i.modify_time,
        modify_user: i.modify_user,
        pattern: i.pattern,
        standard: i.standard,
        type_id: i.type_id,
      }))
      let arr = this.spotCheckList.concat(tmp)
      let newArr = this.uniqueFun(arr, 'item_id')
      this.spotCheckList = newArr
      this.addspotCheckShow = false
      this.maintainShows = false
    },
    uniqueFun(arr, type) {
      const res = new Map()
      return arr.filter((a) => !res.has(a[type]) && res.set(a[type], 1))
    },
    // 创建数据
    createItems() {
      this.createItem()
    },
    // 编辑
    editItemTask(v) {
      this.pageLoading = true
      let url = this.api + 'getbyid'
      this.$request(url, {
        id: v.id,
      })
        .then((r) => {
          this.spotCheckList = []
          this.data = r
          this.spotCheckList = r.detail
          this.editFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    submits() {
      let additems = []
      this.spotCheckList.map((i) => {
        additems.push(i.id)
      })
      let delIds = []
      this.delitems.forEach((i) => {
        delIds.push(i.item_id)
      })
      let Data = {
        data: this.data,
        additems: additems,
        delitems: delIds,
      }
      this.data = Data
      this.submit()
    },
    // 添加人员
    addUserClick(v, type) {
      this.addUserType = type
      this.taskId = v.id
      this.selectVisible = true
      this.$nextTick(() => {
        this.$refs.useselect.open(1, [])
      })
    },
    useSelectChange(data) {
      if (data.length > 1) return this.$message.warning('请选择一个用户')
      let Data = {
        id: this.taskId,
        owner: data[0].id,
      }
      if (this.addUserType) {
        this.$request(this.api + 'TaskAssign', Data, 'post')
          .then((r) => {
            this.$message.success('指派成功')
            this.getList()
          })
          .finally(() => {
            this.taskId = ''
          })
      } else {
        this.$request(this.api + 'TaskReassign', Data, 'post')
          .then((r) => {
            this.$message.success('转派成功')
            this.getList()
          })
          .finally(() => {
            this.taskId = ''
          })
      }
    },
    // 获取岗位
    post() {
      let Data = {
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmEquipmentPost/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.userData = list.map((i) => ({
          label: i.positions_name,
          value: i.id,
        }))
      })
    },
    useSelectClose() {
      this.selectVisible = false
      this.taskId = ''
    },
    // 开始维护
    taskMaintain(v) {
      this.$request(this.api + 'TaskMaintain/' + v.id, {}, 'post').then((r) => {
        this.taskrowStatas = v.task_status
        this.taskId = v.id
        this.replaceData = {
          machine_id: v.machine_id,
          executor_type: 2,
          page: 1,
          size: 999,
        }
        this.GetTpmEquipmentPartLogList()
        let params = {
          taskid: v.id,
        }
        // 获取维护的保养项
        this.$request(this.api + 'GetMaintenanceTaskDetail', params).then((r) => {
          this.taskList = r
          this.maintainShow = true
        })
      })
    },
    GetTpmEquipmentPartLogList() {
      this.$request(this.baseUrl + 'Tpm/TpmEquipmentPart/GetTpmEquipmentPartLogList', this.replaceData, 'post').then(
        (r) => {
          const { list } = r
          this.replaceList = list
        },
      )
    },
    // 审核
    toAudit(v) {
      this.taskrowStatas = 9 //大于2的时候禁止上传
      this.taskId = v.id
      let params = {
        taskid: v.id,
      }
      this.$request(this.api + 'GetMaintenanceTaskDetail', params).then((r) => {
        this.taskList = r
        this.maintainShow = true
      })
    },
    // 提交审核
    taskAuditComfirm(val) {
      let Data = {
        id: this.taskId,
        audit_note: val.audit_note,
        audit_result: val.audit_result,
      }
      this.$request(this.api + 'TaskAuditConfirm', Data, 'post').then((r) => {
        this.$message.success('提交成功')
        this.getList()
        this.maintainShow = false
      })
    },
    // 保存点检维护
    saveTask(val) {
      if (val) {
        let Data = {
          task_id: this.taskId,
          details: this.taskList,
        }
        this.$request(this.api + 'SubmitTask', Data, 'post')
          .then((r) => {
            this.$message.success('提交成功')
            this.getList()
            this.maintainShow = false
          })
          .finally(() => {
            this.taskId = ''
          })
      } else {
        this.$request(this.api + 'SaveMaintenanceTaskDetail', this.taskList, 'post')
          .then((r) => {
            this.$message.success('保存成功')
            this.research()
            this.maintainShow = false
          })
          .finally(() => {
            this.taskId = ''
          })
      }
    },
    // 上传
    uploadOnchange(file, fileList) {
      let f = file.raw
      const isLt20M = f.size / 1024 / 1024 < 20
      if (!isLt20M) {
        fileList.splice(fileList.indexOf(f), 1)
        return this.$message.error('上传档案大小不能超过 20MB!')
      }
      alert(9)
      this.formData.append('file', f)
    },
    // 清除附件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定要删除${file.name}?`, 提示, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (file.FileId) {
          // 已经有附件了,进行删除
          this.removeFiles.push(file.FileId)
        } else {
          this.formData = new FormData()
          // 刚上传没有点确定
          fileList.forEach((i) => {
            if (!i.FileId && i.name != file.name) {
              this.formData.append('file', i.raw)
            }
          })
        }
      })
    },
    // 预览
    onPreview(file) {
      alert('没有接口看个毛')
    },
    // 超过最大上传数
    handleExceed() {
      return this.$message.warning('最多只能上传5张图片')
    },
    // 获取匹配数据
    getMatchingData(val, code) {
      if (code == 'method') {
        let tmp = this.methodOptions.find((i) => i.value == val)
        return tmp ? tmp.label : ''
      }
    },
    selectionChange(val) {
      this.deleteSpotList = val
    },
    // 获取点检方法
    getpositions() {
      this.$request(this.$api.dictionary + 'getdirectchildren', {
        parentType: 'maintainMethod',
      }).then((r) => {
        this.methodOptions = r.map((i) => ({
          label: i.label,
          value: i.value * 1,
        }))
      })
    },
  },
}
</script>

<style lang="less" scoped></style>